package net.ujacha;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

import javax.imageio.ImageIO;

import org.apache.commons.io.IOUtils;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ByteArrayBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public class GoogleImageSearch {

	private final static String UPLOAD_URL = "http://images.google.com/searchbyimage/upload";

	public String uploadImage(File imageFile) throws Exception {

		
		DefaultHttpClient client = new DefaultHttpClient();
		
		String fingerprint = null;

		if (!imageFile.isFile()) {
			throw new FileNotFoundException(imageFile.getPath() + " not found.");
		}

		BufferedImage image = ImageIO.read(imageFile);

		// System.out.println(image.toString());

		byte[] bytes = IOUtils.toByteArray(new FileInputStream(imageFile));

		int bih = image.getHeight();
		int biw = image.getWidth();

		String filename = imageFile.getName();

		HttpPost post = new HttpPost(UPLOAD_URL);

		MultipartEntity entity = new MultipartEntity();

		ByteArrayBody body = new ByteArrayBody(bytes, filename);

		entity.addPart("image_url", new StringBody(""));
		entity.addPart("btnG", new StringBody("Search"));
		entity.addPart("encoded_image", body);
		entity.addPart("image_content", new StringBody(""));
		entity.addPart("filename", new StringBody(""));
		entity.addPart("hl", new StringBody("en"));
		entity.addPart("bih", new StringBody(Integer.toString(bih)));
		entity.addPart("biw", new StringBody(Integer.toString(biw)));

		post.setHeader(
				"User-Agent",
				"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.64 Safari/537.31");

		post.setEntity(entity);

		HttpResponse response = null;

		response = client.execute(post);

		int code = response.getStatusLine().getStatusCode();

		// System.out.println("CODE = " + code);

		if (code == 302) {

			String location = null;

			Header[] headers = response.getHeaders("Location");

			if (headers != null && headers.length > 0) {
				location = headers[0].getValue();
			} else {
				throw new Exception("redirect location not found");
			}

			EntityUtils.consumeQuietly(response.getEntity());

			System.out.println(location);

			HttpGet get = new HttpGet(location);

			get.setHeader(
					"User-Agent",
					"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.64 Safari/537.31");

			response = client.execute(get);

			code = response.getStatusLine().getStatusCode();

			if (code != 200) {
				throw new Exception("result is not 200 at redirect page : \n\t"
						+ location);
			}

			String html = EntityUtils.toString(response.getEntity());

			EntityUtils.consumeQuietly(response.getEntity());

			// System.out.println(html);

			Document document = Jsoup.parse(html);

			Elements elements = document.select("#imagebox_bigimages");

			if (elements != null && elements.size() > 0) {
				Element element = elements.first();

				// System.out.println(element.toString());

				System.out.println(element.select("h3 a").first().toString());

			} else {
				throw new Exception("elements not found : "
						+ "#imagebox_bigimages");
			}

		} else {

			throw new Exception("result is not 302 at image upload");

		}
		
		
		return fingerprint;
	}

	public static void main(String[] args) {
		try {
			GoogleImageSearch search = new GoogleImageSearch();

			File imageFile = new File("D:/SHKIM/WALL/30833842_MlPXq2Ns_BCF6C1F6.jpg");
			String result = search.uploadImage(imageFile);

			System.out.println(result);

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

}